package cn.szzsi.service;

import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.Orders;
import cn.szzsi.common.model.UserBalance;
import com.jfinal.plugin.activerecord.Db;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 资金余额业务类
 * Created by zhengy on 2017/2/27.
 */
public class UserBalanceService {
    public static final UserBalanceService service = new UserBalanceService();

    /**
     * 余额明细,若表里面不存在该会员,才会创建,否则直接更新,不执行此方法
     * @param member 会员实体类
     * @param balance 资金余额
     * @param point 积分余额
     * @param cashing 提现金额
     */
    public void saveInfo(Member member, BigDecimal balance, Integer point,BigDecimal cashing){
        UserBalance ub=new UserBalance();
        ub.set("id", CommonUtil.getUUID());
        ub.set("mid",member.getStr("id"));
        ub.set("balance",balance);
        ub.set("cashing",cashing);
        ub.set("point",point);
        ub.set("freezeMoney",new BigDecimal(0));
        ub.set("shopId",member.getStr("shopId"));
        ub.set("createDate",new Date());
        ub.save();
        //保存完之后更新冻结金额
        ub.set("freezeMoney",getFreezeMoney(member)).update();
    }


    /**
     *  更新余额
     * @param member 会员实体类
     * @param balance 余额
     */
    public void updateBalance(Member member, BigDecimal balance){
        //1.查看结果表是否存在该会员信息
        UserBalance ub= UserBalance.dao.findByMemberId(member.getStr("id"));
        if(ub!=null){//若存在,则直接更新
            ub.set("balance",ub.getBigDecimal("balance").add(balance)).update();
            ub.set("freezeMoney",getFreezeMoney(member)).update();//更新冻结金额
        }else{//2.若不存在,则新增
            saveInfo(member,balance,0,new BigDecimal(0));
        }
    }

    /**
     *  更新积分
     * @param member 会员实体类
     * @param point  积分
     */
    public void updatePoint(Member member,Integer point){
        //查看结果表是否存在该会员信息
        UserBalance ub= UserBalance.dao.findByMemberId(member.getStr("id"));
        if(ub!=null){//1.若存在,则直接更新
            ub.set("point",ub.getInt("point")+point).update();
        }else{//2.若不存在,则新增
            saveInfo(member,new BigDecimal(0),point,new BigDecimal(0));
        }
    }

    /**
     *  更新提现金额
     * @param member 会员实体类
     * @param cashing 提现金额
     */
    public void updateCashing(Member member, BigDecimal cashing){
        //1.查看结果表是否存在该会员信息
        UserBalance ub= UserBalance.dao.findByMemberId(member.getStr("id"));
        if(ub!=null){//1.若存在,则直接更新
            ub.set("balance",ub.getBigDecimal("balance").subtract(cashing));//更新余额
            ub.set("cashing",ub.getBigDecimal("cashing").add(cashing));//更新提现余额
            ub.update();
            //更新冻结金额
            ub.set("freezeMoney",getFreezeMoney(member)).update();
        }else{//2.若不存在,则新增
            saveInfo(member,new BigDecimal(0),0,cashing);
        }
    }

    /**
     * 查看总金额
     * @param member
     * @return
     */
    public BigDecimal getBalance(Member member){
        String expectSql="select balance from mall_user_balance where mid='"+member.getId()+"'";
        BigDecimal totalProfit = Db.queryColumn(expectSql);
        if(totalProfit==null){
            totalProfit = new BigDecimal(0);
        }
        if(totalProfit.compareTo(new BigDecimal(0))<0){
            totalProfit = new BigDecimal(0);
        }
        //totalProfit=totalProfit.setScale(0, BigDecimal.ROUND_DOWN);//保留整数部分
        return totalProfit;
    }

    /**
     * 获取会员冻结金额
     * @param member
     */
    public BigDecimal  getFreezeMoney(Member member){
        //查看该用户是否购买过商品
        Orders orders=Orders.dao.isAlreadyBuy(member);
        if(orders==null){
            UserBalance userBalance=UserBalance.dao.findByMemberId(member.getId());
            return userBalance.getBalance();
        }else{//正式会员
            //根据直谏人数来判断是否冻结金额
            BigDecimal freezeMoney = null;
            /*long num = Db.queryLong("select count(*) from mall_member where pid = '"+member.getStr("id")+"' and memberRankId='dafc86f6aee04a8aa9c722689ef65b3y'");
            if(num == 1){
                freezeMoney = Db.queryColumn("select sum(addMoney) from mall_user_balance_detail where mid = ? and type = '0' and (level =2 or level = 3)",member.get("id"));
            }else if(num == 2){
                freezeMoney = Db.queryColumn("select sum(addMoney) from mall_user_balance_detail where mid = ? and type = '0' and (level = 3)",member.get("id"));
            }else if(num >2){
                freezeMoney = new BigDecimal(0);
            }*/
            if(freezeMoney == null){
                freezeMoney = new BigDecimal(0);
            }
            return freezeMoney;
        }
    }
    /**
     * 可提金额(总金额-冻结金额)
     * @param member
     * @return
     */
    public BigDecimal getAvailBalance(Member member){
        BigDecimal balance=getBalance(member);//总额
        BigDecimal freezeMoney=getFreezeMoney(member);//可提金额
        /*BigDecimal availBalance=balance.subtract(freezeMoney);
        if(availBalance.compareTo(new BigDecimal(0))<0){
            availBalance=new BigDecimal(0);
        }*/
        return balance;
    }




    /**
     *  更新余额(针对会员支付返佣的,因为订单支付加了事物处理,冻结金额获取是分销之前的
     *  ,这样一来就不能实时获取被返佣人的冻结金额,后续可以考虑定时器)
     * @param member 会员实体类
     * @param balance 充值金额
     * @param level 该笔分销所在该会员的等级
     */
    public void updateBalanceForFenXiao(Member member, BigDecimal balance,Integer level){
        //1.查看结果表是否存在该会员信息
        UserBalance ub= UserBalance.dao.findByMemberId(member.getId());
        if(ub!=null){//若存在,则直接更新
            ub.set("balance",ub.getBalance().add(balance)).update();
            ub.set("freezeMoney",new BigDecimal(0)).update();//更新冻结金额
        }else{//2.若不存在,则新增
            saveInfo(member,balance,0,new BigDecimal(0));
        }
    }

    /**
     * 针对会员支付返佣的,因为订单支付加了事物处理,冻结金额获取是分销之前的
     *  ,这样一来就不能实时获取被返佣人的冻结金额,后续可以考虑定时器
     * @param member
     * @param level 该笔分销所在该会员的等级
     * @param fenXiaoMoney 分销金额
     * @return
     */
    public BigDecimal getFreezeMoneyForFenXiao(Member member,BigDecimal fenXiaoMoney,Integer level){
        //System.out.println(member.getStr("id"));
        //查看该用户是否购买过商品
        Orders orders=Orders.dao.isAlreadyBuy(member);
        if(orders==null){//如果没有购买,则金额全部冻结
            UserBalance userBalance=UserBalance.dao.findByMemberId(member.getId());
            return userBalance.getBalance();
        } else{//如果该用户已经买过,则根据直谏人数判断冻结金额的多少(暂时将冻结金额置为0,后续如果有需求,再做调整)
            BigDecimal freezeMoney = null;
            /*long num = Db.queryLong("select count(*) from mall_member where pid = '"+member.getId()+"' and memberRankId='dafc86f6aee04a8aa9c722689ef65b3y'");
            if(num == 1){//推荐一个人,冻结金额为二三级的返佣
                freezeMoney = Db.queryColumn("select IFNULL(sum(addMoney),0) from mall_user_balance_detail where mid = ? and type = '0' and (level =2 or level = 3)",member.get("id"));
                if(level==2 || level==3){
                    freezeMoney=freezeMoney.add(fenXiaoMoney);
                }
            }else if(num == 2){//推荐两个人,冻结金额为三级的返佣
                freezeMoney = Db.queryColumn("select IFNULL(sum(addMoney),0) from mall_user_balance_detail where mid = ? and type = '0' and (level = 3)",member.get("id"));
                if(level==3){
                    freezeMoney=freezeMoney.add(fenXiaoMoney);
                }
            }else if(num >2){//推荐人数大于两人,冻结金额为0
                freezeMoney = new BigDecimal(0);
            }*/
            if(freezeMoney == null){//没有推荐,则没有冻结金额
                freezeMoney = new BigDecimal(0);
            }
            return freezeMoney;
        }
    }

}
